/**
 * Created by webrx on 2024/5/9.
 */

import axios, {type AxiosError, type AxiosRequestConfig, type AxiosResponse, type AxiosInstance, AxiosHeaders} from 'axios'
import {ElMessage as message, ElLoading as eloading} from 'element-plus'

// 定义自己的响应类型
interface MyAxiosResponse<T = any, D = any> extends AxiosResponse<T, D> {
    [key: string]: any
}


//创建axios 对象实例
const http: AxiosInstance = axios.create({
    baseURL: 'http://127.0.0.1:8888/api/private/v1/',
    timeout: 5000,
    headers: {'Authorization': ''}
})

//加载配置
let loadingInstance: any
let requestNum: number = 0
let loading: boolean = true

//加载动画
const addLoading = () => {
    // 防止重复弹出
    requestNum++;
    if (requestNum == 1) {
        loadingInstance = eloading.service({fullscreen: true})
    }
}

// 关闭 加载动画
const cancelLoading = () => {
    requestNum--
    // 关闭 加载动画
    if (requestNum === 0) loadingInstance?.close()
}


// 错误处理
function showError(error: any) {
    // token过期，清除本地数据，并跳转至登录页面
    if (error.code === 403) {
        // to re-login
        //store.dispatch('user/loginOut')
    } else {
        message({
            message: error.msg || error.message || '服务异常',
            type: 'error',
            duration: 3 * 1000
        })
    }
}

// 请求拦截器
http.interceptors.request.use(
    config => {
        //加载动画
        if (loading) addLoading()
        // 可以在这里添加请求头等信息
        //let token = store.getters['getToken']
        //let token = JSON.parse(localStorage.getItem('app')).Authorization
        let token = localStorage.getItem('token')
        if (token) {
            config.headers['Authorization'] = token
        }
        return config
    },
    (error: AxiosError) => {
        // 请求错误处理
        //console.log(error) // for debug
        Promise.reject(error)
    }
);

// 响应拦截器
http.interceptors.response.use(
    (response: AxiosResponse) => {
        // 对响应数据做处理，例如只返回data部分
        // const res = response.data
        // if (res.code === 200) {
        //     return res
        // } else {
        //     showError(res)
        //     return Promise.reject(res)
        // }

        // 关闭加载 动画
        if (loading) cancelLoading();
        if (response.data.meta.status !== 200) {
            message.error(response.data.meta.msg)
        }
        //返回参数
        return response.data

    },
    (error: AxiosError) => {
        // 关闭加载 动画
        if (loading) cancelLoading();
        /***** 接收到异常响应的处理开始 *****/
        if (error && error.response) {
            // 1.公共错误处理
            // 2.根据响应码具体处理
            switch (error.response.status) {
                case 400:
                    error.message = '错误请求'
                    break;
                case 401:
                    error.message = '未授权，请重新登录'
                    break;
                case 403:
                    error.message = '拒绝访问'
                    break;
                case 404:
                    error.message = '请求错误,未找到该资源'
                    break;
                case 405:
                    error.message = '请求方法未允许'
                    break;
                case 408:
                    error.message = '请求超时'
                    break;
                case 500:
                    error.message = '服务器端出错'
                    break;
                case 501:
                    error.message = '网络未实现'
                    break;
                case 502:
                    error.message = '网络错误'
                    break;
                case 503:
                    error.message = '服务不可用'
                    break;
                case 504:
                    error.message = '网络超时'
                    break;
                case 505:
                    error.message = 'http版本不支持该请求'
                    break;
                default:
                    error.message = `连接错误${error.response.status}`
            }
        } else {
            // 超时处理
            if (JSON.stringify(error).includes('timeout')) {
                error.message = '服务器响应超时，请刷新当前页'
            } else {
                error.message = '连接服务器失败'
            }
        }
        //提示
        message.error(error.message)
        /***** 处理结束 *****/
        return Promise.resolve(error.response)
    }
)

//get 获取数据 请求 params
export const get = (url: string, params?: any) => {
    return http({url, method: 'GET', params})
}

//delete 删除 请求 params
export const del = (url: string, params: any) => {
    return http({url, method: 'DELETE', params})
}

//post 添加 请求
export const post = (url: string, data: any) => {
    return http({url, method: 'POST', data})
}

//put 更新 请求
export const put = (url: string, data: any) => {
    return http({url, method: 'PUT', data})
}

//patch 批量更新 请求
export const patch = (url: string, data: any) => {
    return http({url, method: 'PATCH', data})
}
